package aod.android.com.bernay.http;

import android.util.Log;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;

import aod.android.com.bernay.BernayApp;
import chen.lion.hilib.util.LogUtils;

/**
 * 七牛简易工具类
 */
public class QNTool {

    private static boolean isUp = false;

    /**
     * 简单上传
     * @param file
     * @param token
     * @param listener
     */
    public static void post(File file, String token, final OnQNListener listener){
        isUp = false;
        BernayApp.mUploadManager.put(file, System.currentTimeMillis()+"-test", token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {
                            listener.onSuccess(key);
                        } else {
                            listener.onFild(new Exception("上传文件失败"));
                        }
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, new UploadOptions(null, null, false, new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
                        LogUtils.e(percent+"");
                        listener.onProgress(key, percent);
                    }
                }, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
                        return isUp;
                    }
                }));
    }

    public static void cancell(){
        isUp =true;
    }


    public interface OnQNListener{
        void onSuccess(String fileKey);
        void onFild(Exception e);
        void onProgress(String key,double progress);
    }
}
